import { DistanceMeasure } from "./distance"
import { TriangleMeasure } from "./Triangle"
import { AreaMeasure } from "./AreaMeasure"
import * as Cesium from "cesium"
import { MeasureStyle } from "./style"

type MeasureType = "distance" | "triangle" | "area"

/**
 * @description 测量工具
 * + 操作方式：左键拾取坐标，右键结束；
 * + 测量类型：支持直线距离测量、面积测量、三角距离测量；默认值为直线距离测量；
 * + 支持顶点编辑：已绘制完成的测量图形支持顶点拖动，鼠标悬停在顶点上，按下鼠标左键拖动。
 * @param {Viewer} viewer - Cesium Viewer 实例
 * @param {MeasureStyle} styleOption - 支持自定义画笔样式
 * @example
 * //实例化一个测量工具
 * const measure = new Measure(fair.viewer)
 *
 * //开始距离测量
 * measure.start()
 *
 * //开始面积测量
 * measure.type = 'area'
 * measure.start()
 *
 * //开始三角测量
 * measure.type = 'triangle'
 * measure.start()
 *
 * //清空已有测量实体
 * measure.clear()
 * //销毁测量实例
 * measure.destroy()
 */
export class Measure {
  private _type: MeasureType = "distance"
  get type() {
    return this._type
  }
  set type(val) {
    if (val != this._type) {
      this._type = val
      this.toggleMeasureTool()
    }
  }
  isMeasuring: boolean = false
  distanceMeasure?: DistanceMeasure
  triangleMeasure?: TriangleMeasure
  areaMeasure?: AreaMeasure
  currentTool?: DistanceMeasure | TriangleMeasure | AreaMeasure
  constructor(
    public viewer: Cesium.Viewer,
    public styleOption?: MeasureStyle,
  ) {
    this.currentTool = this.distanceMeasure = new DistanceMeasure(
      viewer,
      styleOption,
    )
  }

  //开始测量
  start() {
    this.currentTool?.start()
    this.isMeasuring = true
  }

  //结束测量
  end() {
    this.currentTool?.end()
    this.isMeasuring = false
  }

  //清空
  clear() {
    this.areaMeasure?.clear()
    this.distanceMeasure?.clear()
    this.triangleMeasure?.clear()
  }

  //切换测量工具
  private toggleMeasureTool() {
    if (this.isMeasuring) {
      this.currentTool?.end()
    }

    switch (this.type) {
      case "distance":
        this.currentTool = this.distanceMeasure
        break
      case "triangle":
        if (!this.triangleMeasure) {
          this.triangleMeasure = new TriangleMeasure(
            this.viewer,
            this.styleOption,
          )
        }
        this.currentTool = this.triangleMeasure
        break
      case "area":
        if (!this.areaMeasure) {
          this.areaMeasure = new AreaMeasure(this.viewer, this.styleOption)
        }
        this.currentTool = this.areaMeasure
        break
    }
    if (this.isMeasuring) {
      this.currentTool?.start()
    }
  }
}
